
import * as vscode from 'vscode';
import fs from 'fs';
import path from 'path';
import { HighlightjsParam } from '../store/types';
import { AgentViewController } from '../core/AgentViewController';

function findCSSFiles(dir: string): string[] {
    let results: string[] = [];
    fs.readdirSync(dir).forEach(file => {
        file = path.join(dir, file);
        const stat = fs.statSync(file);
        if (stat && stat.isDirectory()) {
            results = results.concat(findCSSFiles(file));  // 如果是目录，则递归调用	
        }	
        else {
            if (path.extname(file).toLowerCase() === '.css') {
                results.push(file);  // 如果是CSS文件，则添加到结果数组中	
            }	
        }
    });
    return results;
}

export class HighlightHelper {
	constructor(private readonly controller: AgentViewController) {}	

	getThemes(): string[] {
		const stylesUri: vscode.Uri = vscode.Uri.joinPath(this.controller.context.extensionUri, 'ui', 'node_modules', 'highlight.js', 'styles');
		const dir = stylesUri.fsPath;
		const results: string[] = findCSSFiles(dir);
		return results.map(file => {
			return path.basename(file, '.css');
		});
	}

	getThemeContent(themeName: string) : string {
		const stylesUri: vscode.Uri = vscode.Uri.joinPath(this.controller.context.extensionUri, 'ui', 'node_modules', 'highlight.js','styles');
		const dir = stylesUri.fsPath;
		const results: string[] = findCSSFiles(dir);	
		const themeFile = results.find(file => {
			return path.basename(file, '.css') === themeName;	
		});
		if (themeFile) {
			return fs.readFileSync(themeFile, 'utf-8');	
		}
		return '';
	}
	
	getTheme(themeName = 'vs2015') : HighlightjsParam {
		return {
			theme: themeName,
			themes: this.getThemes(),
			content: this.getThemeContent(themeName),
		};
	}
}